package com.ushine.web.communication.netty;

import com.ushine.web.communication.netty.handler.DataResolveHandler;
import com.ushine.web.communication.netty.handler.HeartbeatHandler;
import com.ushine.web.communication.netty.handler.RegisterHandler;
import com.ushine.web.communication.netty.proto.Message;
import com.ushine.web.communication.netty.service.INettyService;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.protobuf.ProtobufDecoder;
import io.netty.handler.codec.protobuf.ProtobufEncoder;
import io.netty.handler.codec.protobuf.ProtobufVarint32FrameDecoder;
import io.netty.handler.codec.protobuf.ProtobufVarint32LengthFieldPrepender;
import io.netty.handler.timeout.IdleStateHandler;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.TimeUnit;

/**
 * @Author: yls
 * @Date 2022/5/11 9:43
 * @Description: 通道初始化器
 * @Version 1.0
 **/
@Slf4j
public class ServerChannelInitializer extends ChannelInitializer<SocketChannel> {

    /**
     * 通信服务
     */
    private final INettyService nettyService;

    public ServerChannelInitializer(INettyService nettyService) {
        this.nettyService = nettyService;
    }

    @Override
    protected void initChannel(SocketChannel socketChannel) throws Exception {
        ChannelPipeline pipeline = socketChannel.pipeline();
        //心跳超时处理器
        pipeline.addLast(new IdleStateHandler(30, 0, 0, TimeUnit.SECONDS));
        //解决粘包问题
        pipeline.addLast(new ProtobufVarint32FrameDecoder());
        //解码处理器
        pipeline.addLast(new ProtobufDecoder(Message.Instruction.getDefaultInstance()));
        //序列化时设置编码长度
        pipeline.addLast(new ProtobufVarint32LengthFieldPrepender());
        //编码处理器
        pipeline.addLast(new ProtobufEncoder());
        //心跳处理器
        pipeline.addLast(new HeartbeatHandler());
        //注册处理器
        pipeline.addLast(new RegisterHandler(nettyService));
        //数据处理器
        pipeline.addLast(new DataResolveHandler(nettyService));

    }

}
